import { useState, useEffect, useCallback } from 'react';
import { Popup, Picker } from 'react-vant';

import SvgIcon from '@/components/SvgIcon/index';

import useStore from '@/store/index';
import { staticActionList, appColumn, deviceId } from '@/utils/staticData';
import { IActionData } from '@/types/IContext';

import './index.less';

interface ActionProps {
  onActionChange: (value: number, type: string) => void;
}
export default function Action({ onActionChange }: ActionProps) {
  const Hejia = (window as any).Hejia;
  const { stopLoop, info, scheduleLoopStart } = useStore();
  const { isOnline, fault, state: status, mode, booking } = info


  const [visibleStr, setVisibleStr] = useState<String>('');
  const [appTitle, setAppTitle] = useState('预约');
  const [columns] = useState(appColumn());

  const POPUP_STATES = {
    appVisible: 'appointment'
  } as const;

  const setDeviceParam = (content: number) => {
    Hejia.setControlParam(
      {
        // deviceId,
        parameters: {
          param: [{ name: 'booking', content }]
        }
      },
      () => console.log('success'),
      (msg: string, obj: any) => console.log(msg + obj.resultCode + obj.resultCodeMessage)
    );
  };

  let _staticActionList = staticActionList;

  const [appValue, setAppValue] = useState<string[]>(['30']);
  const [disabledList, setDisabledList] = useState<string[]>(['']);

  const getDisabled = useCallback((): void => {
    const isDisabled = !isOnline || [1, 2, 3].includes(status) || fault > 0;
    // 检查特定模式下是否禁用预约功能
    const isAppointmentDisabledMode = status === 0 && [0, 1, 3, 4, 9].includes(mode);

    const disabledItems = (isDisabled || isAppointmentDisabledMode) ? ['appointment'] : [''];

    setDisabledList(disabledItems);
  }, [isOnline, status, fault, mode]);

  useEffect(() => {
    getDisabled();
  }, [getDisabled]);



  // 预约
  useEffect(() => {
    setAppValue([`${booking}`]);
    _staticActionList[0].val = booking ? `${booking}分钟` : '未设置';
  }, [booking]);

  const handleClose = () => {
    setVisibleStr('');
    scheduleLoopStart()
  };

  const onAppCancel = () => {
    _staticActionList[0].val = '未设置';
    onActionChange(0, 'appointment');
    handleClose();
    setDeviceParam(0);
  };

  const onClickAction = (key: string): void => {
    setVisibleStr(key);
    if (key === 'appointment') {
      setAppTitle(booking ? '编辑预约' : '预约');
    }
  };

  const handleConfirm = (val: (string | number)[]) => {
    _staticActionList[0].val = `${val}分钟`;
    onActionChange(Number(val), 'appointment');
    handleClose();
    setDeviceParam(Number(val));
  };

  const itemEle = _staticActionList.map((item: IActionData) => {
    return (
      <div className="action-item" key={item.id}>
        {disabledList.includes(item.key) && <div className="mask"></div>}
        <div className="content" onClick={() => onClickAction(item.key)}>
          <div className="icon">
            <SvgIcon name={`${item.svg}`} size="34" />
          </div>
          <div className="left">
            <div className="title">{item.title}</div>
            <div className="num">{item.val}</div>
          </div>
        </div>
      </div>
    );
  });

  return (
    <div className="action">
      {itemEle}

      {/* 预约弹框 */}
      <Popup
        round
        visible={POPUP_STATES.appVisible === visibleStr}
        position="bottom"
        onOpen={stopLoop}
        onClose={handleClose}
      >
        <div className="time-wrapper">
          <Picker
            value={appValue}
            title={appTitle}
            placeholder=""
            confirmButtonText="确定"
            columns={columns}
            onCancel={() => setVisibleStr('')}
            onConfirm={handleConfirm}
          />
          <div className="unit">分钟</div>
        </div>
        {!!booking && (
          <div className="btn-cancel" onClick={onAppCancel}>
            取消预约
          </div>
        )}
      </Popup>
    </div>
  );
}
